/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package xmlopdracht2;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import javax.swing.filechooser.FileFilter;


/**
 *
 * @author Gerben Gernaat
 */
public class SimpleFileFilter extends FileFilter
{
  private String desc;
  private List<String> extensions;
  private boolean showDirectories;

  /**
   * @param name example: "Data files"
   * @param glob example: "*.txt|*.csv"
   */
  public SimpleFileFilter(String name, String globs)
  {
    extensions = new ArrayList<String>();
    for (String glob : globs.split("\\|"))
    {
      if (!glob.startsWith("*."))
      {
        throw new IllegalArgumentException("expected list of globs like \"*.txt|*.csv\"");
      }
      // cut off "*"
      // store only lower case (make comparison case insensitive)
      extensions.add(glob.substring(1).toLowerCase());
    }
    desc = name + " (" + globs + ")";
  }

  public SimpleFileFilter(String name, String globs, boolean showDirectories)
  {
    this(name, globs);
    this.showDirectories = showDirectories;
  }

  @Override
  public boolean accept(File file)
  {
    if (showDirectories && file.isDirectory())
    {
      return true;
    }
    String fileName = file.toString().toLowerCase();

    for (String extension : extensions)
    {
      if (fileName.endsWith(extension))
      {
        return true;
      }
    }
    return false;
  }

  @Override
  public String getDescription()
  {
    return desc;
  }

  /**
   * @return includes '.'
   */
  public String getFirstExtension()
  {
    return extensions.get(0);
  }
}
